//
//  Energy.m
//  ProjectL
//
//  Created by Nguyen Tan Loc on 8/16/13.
//  Copyright (c) 2013 Nguyen Tan Loc. All rights reserved.
//

#import "Energy.h"
#import "MainGameScene.h"
#import "Utility.h"

@implementation Energy
@synthesize _isCollect = mIsCollect;

-(id) init
{
    if (self = [super initWithSpriteFrameName:[self getSpriteFrameName]])
    {
        mIsCollect = false;
        [self setIgnoreBodyRotation:NO];
        [self createBody];
//        [self setColor:ccc3(160, 118, 223)];
                [self setColor:ccc3(181, 141, 234)];
    }
    
    return self;
}

-(void) createBody
{
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(0, 0);
    
    _b2Body = PhysicSystem::getInstance()->mWorld->CreateBody(&bodyDef);
    
    b2CircleShape shape;
    shape.m_radius = (self.contentSize.width / 2) / PTM_RATIO;
    
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &shape;
    fixtureDef.filter.categoryBits = [self getObjectType];
    fixtureDef.filter.maskBits = MASK_BIT_ENERGY;
    fixtureDef.isSensor = true;
    _b2Body->CreateFixture(&fixtureDef);
    
    [self setPTMRatio:PTM_RATIO];
    _b2Body->SetUserData(self);
}

-(void) addActions:(NSArray *)actions
{
    mListAction = [actions retain];
}

-(void) startAction
{
    if (mListAction != nil)
    {
        for (int i = 0; i < mListAction.count; i++)
        {
            [self runAction:[mListAction objectAtIndex:i]];
        }
    }
}

-(void) stopAction
{
    [self stopAllActions];
}

-(void) collect
{
    [[Utility getInstance] playEffect:SOUND_ENERGY_COLLECT];
    mIsCollect = YES;
    [self stopAllActions];
    [self setIsUseBox2xAnchorPoint:NO];
    
    CGPoint des = [[MainGameScene getInstance]._mainGameUI getIconEnergyPosition];
    des = ccpAdd(des, ccpSub([self position], [self getRealPosition]));
    CCMoveTo *moveTo = [CCMoveTo actionWithDuration:1.0 position:des];
    CCEaseExponentialOut *ease = [CCEaseExponentialOut actionWithAction:moveTo];
    CCCallBlock *callBlock = [CCCallBlock actionWithBlock:^{
        [self setVisible:NO];
        [[MainGameScene getInstance]._mainGameUI updateEnergy];
    }];
    
    CCSequence *sequence = [CCSequence actionOne:ease two:callBlock];
    [self runAction:sequence];
    [LevelManager getInstance]._numEnergy++;
//    PhysicSystem::getInstance()->mWorld->DestroyBody(self.b2Body);
//    [self setVisible:NO];
    
}

-(OBJECT_TYPE) getObjectType
{
    return eO_ENERGY;
}

-(NSString *) getSpriteFrameName
{
    return SFN_ENERGY;
}

-(void) dealloc
{
    [super dealloc];
    CCLOG(@"Energy dealloc!");
}

@end
